<?php

/**
 * 73YC 左边导航栏
 * ============================================================================
 * * 版权所有 20013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH . 'includes/cls_json.php');

$json   = new JSON;
$result = array( 'message' => '','error'=>'');
assign_template();
$action=$_REQUEST['act'];
$back_act=$_REQUEST['back_act'];
$smarty->assign('action', $action);


// AJAX记录和删除session
if($action == 'session'){
        $_SESSION[$_POST['obj']] = $_POST['msg'];
}
elseif($action == 'consignee_update'){
    $address_id = intval($_REQUEST['address_id']);
    if($address_id){
        $consignee = get_consignee_list($_SESSION['user_id'],$address_id);
    }else{
        $consignee = $_SESSION['consignee'];
    }
    $consignee['country']  = isset($consignee['country'])  ? intval($consignee['country'])  : 0;
    $consignee['province'] = isset($consignee['province']) ? intval($consignee['province']) : 0;
    $consignee['city']     = isset($consignee['city'])     ? intval($consignee['city'])     : 0;

    $province_list = get_regions(1, $consignee['country']);
    $city_list     = get_regions(2, $consignee['province']);
    $district_list = get_regions(3, $consignee['city']);
    $p_list = selectaddress($consignee['province']);
    $c_list = selectaddress($consignee['city']);
    $d_list = selectaddress($consignee['district']);

    $smarty->assign('address_id',    $address_id);
    $smarty->assign('province_list',    $province_list);
    $smarty->assign('city_list',        $city_list);
    $smarty->assign('district_list',    $district_list);
    $smarty->assign('p_list',    $p_list);
    $smarty->assign('c_list',    $c_list);
    $smarty->assign('d_list',    $d_list);
    $smarty->assign('consignee', $consignee);

    $result['content'] = $smarty->fetch("library/alone.lbi");
    echo $json->encode($result);
    exit;
}
/* 修改保存地址 */ 
elseif ($action == 'act_edit_address' || $action == 'save_consignee')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
    $smarty->assign('lang', $_LANG);
    if($action == 'act_edit_address'){
        foreach (explode('&',$_POST['data']) as $key => $value) {
            $arr = explode('=',$value);
            $data["$arr[0]"] = $arr[1];
        }

        $consignee = set_consignee($data['district'],$data['daodansong_id'],true);
        if(!$consignee) {
            $result['error'] = 1;
            echo $json->encode($result);
            exit;
        }
        $count =  count(get_consignee_list($_SESSION['user_id']));
        $address = array(
            'num'        => $count,
            'user_id'    => $_SESSION['user_id'],
            'address_id' => intval($data['address_id']),
            'country'    => isset($consignee['country'])   ? intval($consignee['country'])  : 0,
            'province'   => isset($consignee['province'])  ? intval($consignee['province']) : 0,
            'city'       => isset($consignee['city'])      ? intval($consignee['city'])     : 0,
            'district'   => isset($consignee['district'])  ? intval($consignee['district']) : 0,
            'daodansong_id' => isset($consignee['daodansong']['area_id'])  ? intval($consignee['daodansong']['area_id']) : 0,
            'address'    => isset($data['address'])   ? compile_str(trim($data['address']))    : '',
            'consignee'  => isset($data['consignee']) ? compile_str(trim($data['consignee']))  : '',
            'mobile'     => isset($data['mobile'])    ? compile_str(make_semiangle(trim($data['mobile']))) : '',
            'best_time'  => isset($data['best_time']) ? compile_str(trim($data['best_time']))  : '',
            'sign_building' => isset($data['sign_building']) ? compile_str(trim($data['sign_building'])) : '',
            );
        if(strlen($address['mobile']) != 11 || !$address['consignee'] || !$address['address']){
            $result['error'] = 1;
            $result['content'] = '手机号码输入错误';
            echo $json->encode($result);
            exit;
        }
        if(!$address['consignee'] || !$address['address']){
            $result['error'] = 1;
            $result['content'] = '地址出错！';
            echo $json->encode($result);
            exit;
        }
        $address_id = update_address($address); // 更新保存用户收货人信息
        if($address_id) $consignee = get_consignee_list($_SESSION['user_id'],$address_id);
        //设定为默认地址
        $sql =  " UPDATE  ".$ecs->table('users').
                " set address_id='$address_id'".
                " WHERE user_id= $_SESSION[user_id]";
        $db->query($sql);

    }else{
        $address_id = intval($_POST['address_id']);
        if($address_id) $consignee = get_consignee_list($_SESSION['user_id'],$address_id);
        set_consignee(intval($consignee['district']),intval($consignee['daodansong']['area_id']),true);
    }
    if ($address_id)
    {
        $smarty->assign('action', 'cur_addr');
        $_SESSION['flow_consignee'] = $consignee; // 记录当前收货人信息
        $area_id = is_buy($consignee)?is_buy($consignee):100;
        $_SESSION['flow_consignee']['area_id']=$area_id;
        $smarty->assign('consignee', $consignee); 
        $sql = "UPDATE " . $ecs->table('cart') . " SET user_id = '$_SESSION[user_id]', area_id = '".$_SESSION['consignee']['area_id']."' WHERE session_id = '".SESS_ID."'";
        $db->query($sql);
        $result['error'] = 0;
        $result['content'] = $smarty->fetch("library/alone.lbi");
    }else{
        $result['error'] = 1;
    }
    echo $json->encode($result);
    exit;
}
/* 修改保存地址 */ 
elseif ($action == 'change_district')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
    $smarty->assign('lang', $_LANG);
        foreach (explode('&',$_POST['data']) as $key => $value) {
            $arr = explode('=',$value);
            $data["$arr[0]"] = $arr[1];
        }

        $consignee = set_consignee($data['district'],$data['daodansong_id'],true);
        if(!$consignee) {
            $result['error'] = 1;
            echo $json->encode($result);
            exit;
        }
        $count =  count(get_consignee_list($_SESSION['user_id']));
        $address = array(
            'num'        => $count,
            'user_id'    => $_SESSION['user_id'],
            'address_id' => intval($data['address_id']),
            'country'    => isset($consignee['country'])   ? intval($consignee['country'])  : 0,
            'province'   => isset($consignee['province'])  ? intval($consignee['province']) : 0,
            'city'       => isset($consignee['city'])      ? intval($consignee['city'])     : 0,
            'district'   => isset($consignee['district'])  ? intval($consignee['district']) : 0,
            'daodansong_id' => isset($consignee['daodansong']['area_id'])  ? intval($consignee['daodansong']['area_id']) : 0,
            'address'    => isset($data['address'])   ? compile_str(trim($data['address']))    : '',
            'consignee'  => isset($data['consignee']) ? compile_str(trim($data['consignee']))  : '',
            'mobile'     => isset($data['mobile'])    ? compile_str(make_semiangle(trim($data['mobile']))) : '',
            'best_time'  => isset($data['best_time']) ? compile_str(trim($data['best_time']))  : '',
            'sign_building' => isset($data['sign_building']) ? compile_str(trim($data['sign_building'])) : '',
            );

        $smarty->assign('action', 'cur_addr');
        $_SESSION['flow_consignee'] = $consignee; // 记录当前收货人信息
        $area_id = is_buy($consignee)?is_buy($consignee):100;
        $_SESSION['flow_consignee']['area_id']=$area_id;
        $smarty->assign('consignee', $consignee); 
        $sql = "UPDATE " . $ecs->table('cart') . " SET user_id = '$_SESSION[user_id]', area_id = '".$_SESSION['consignee']['area_id']."' WHERE session_id = '".SESS_ID."'";
        $db->query($sql);
        $result['error'] = 0;
    echo $json->encode($result);
    exit;
}

/* 获取购物车信息 */
elseif($action == 'cart_info'){
    $order = flow_order_info();
    $consignee = $_SESSION['flow_consignee']?$_SESSION['flow_consignee']:$_SESSION['consignee'];
    $total = order_fee($order, $cart_goods, $consignee);
    $smarty->assign('total', $total);
    $result['content'] = $smarty->fetch("library/alone.lbi");
    $result['content2'] = $smarty->fetch('library/order_total.lbi');
    echo $json->encode($result);
    exit;
}
/* 获取购物车信息指向头部 */
elseif($action == 'cart_info_top'){
    include_once(ROOT_PATH . 'includes/lib_order.php');
    $cart_goods = cart_goods();
    // $cart_goods = cart_goods(); // 取得商品列表，计算合计
    /* 删除购物车里面的extension_code键值 */
    foreach ($cart_goods as $key => $value) {
        if($value['extension_code']&&$value['extension_code'] !="limit"&&$value['extension_code']!='libao'){ 
            $exchange_goods[] = $value;
            unset($cart_goods[$key]);
        }
        if($value['extension_code']=='libao'){
            if($value['parent_id'] && $value['goods_id'] == 0){
                $libaoInfo[$value['parent_id']] = $value;
            }else{
                $libaoGoods[$value['parent_id']][] = $value;
                unset($cart_goods[$key]);
            }
        }
    }

    $smarty->assign('exchange_goods', $exchange_goods);   //刮蛋乐商品列表
    $smarty->assign('goods_list', $cart_goods);
    // $result['content'] = $smarty->fetch("library/alone.lbi");
    $order = flow_order_info();
    $consignee = $_SESSION['flow_consignee']?$_SESSION['flow_consignee']:$_SESSION['consignee'];
    $total = order_fee($order, $cart_goods, $consignee);
    $smarty->assign('total', $total);

    //如果购物车没有商品则返回空
    if(empty($cart_goods)){

    }
    else{
            $result['content'] = $smarty->fetch('library/alone.lbi');
    }
    echo $json->encode($result);
    exit;
}

/* 通过配送地址获取支付方式 */
elseif($action == 'payment'){
    $address_id = !empty($_REQUEST['address_id'])?$_REQUEST['address_id']:"";//获取配送地址ID
    if(!empty($address_id)){
        $consignee =get_address($address_id);
        $smarty->assign('address_id', $address_id);
    }
    else{
        $consignee = !empty($_REQUEST['consignee'])?$_REQUEST['consignee']:$_SESSION['consignee'];
    }
    // 给货到付款的手续费加<span id>，以便改变配送的时候动态显示
    $payment_list = available_payment_list(1, $cod_fee);
    if(isset($payment_list))
    {
        foreach ($payment_list as $key => $payment)
        {
            if ($payment['is_cod'] == '1')
            {
                $payment_list[$key]['format_pay_fee'] = '<span id="ECS_CODFEE">' . $payment['format_pay_fee'] . '</span>';
            }
        }
        //货到付款不支付区域
        if(!is_cod($consignee)){
            unset($payment_list[1]);
        }
    }
   
    $smarty->assign('payment_list', $payment_list);
    $result['content'] = $smarty->fetch("library/alone.lbi");
    echo $json->encode($result);
    exit;
}
/*注册验证*/
elseif($action == 'send_sms'){
        require(dirname(__FILE__) . '/plugins/sms2.php'); //引入接口文件
        $code = rand('100000','999999');
        $mobile = intval($_POST['mobile']);
        $sql = "SELECT user_id FROM " . $ecs->table('users') . " WHERE mobile_phone = '$mobile' OR user_name = '$mobile' OR email = '$mobile'";
        $user_id = $db->getOne($sql);
        if(!$user_id){
            $text = "【鸡蛋美术】您的验证码是:" . $code."该验证码用于用户注册";//短信内容
            $data = send_sms($text, $mobile);
            $data = get_object_vars(json_decode($data));
            if($data['msg'] == 'OK'){
                /*注册验证码*/
                $_SESSION['registerCaptcha'] = $code;
                $_SESSION['mobile'] = $mobile;
            }
        }else{
            $data['msg'] = 'NO';
            $data['message'] = '手机号已经被使用！';
            $data['error'] = 503;
        }
        echo $json->encode($data);
        exit;
}

/* 发送绑定手机短信ajax */
elseif($action == 'send_sms2'){
    require(dirname(__FILE__) . '/plugins/sms2.php'); //引入接口文件
    $mobile = is_numeric($_POST['mobile']) ? intval($_POST['mobile']):''; //POST接送到的用户的手机号
    $code = mt_rand('100000','999999'); //获取一个随机六位数来作为验证码
    //判断是否验证手机
    $sql = "SELECT user_id FROM " . $ecs->table('users') . " WHERE is_mobile_validated = 1 AND mobile_phone = '$mobile'";
    $user_id = $db->getOne($sql);
    $return = array('error' => 0,'content'=>'','message'=>'' );
    if(!$user_id){
        $text = "【鸡蛋美术】您的验证码是:" . $code."该验证码用于绑定手机";//短信内容
        $return = send_sms($text, $mobile);
        $return = get_object_vars(json_decode($return));
        if($return['msg'] == 'OK'){
            $_SESSION['mobileCaptcha'] = $code;
            $_SESSION['mobile'] = $mobile;
        }else{
            $return['error'] = 510;
            $return['message'] = '手机号填写错误！';
        }
    }else{
        $return['error'] = '509';
        $return['message'] = '该手机已被绑定';
    }




    echo $json->encode($return);
    exit;
}



elseif($action == 'is_captcha'){
    if($_SESSION['captcha_time']+600 > time()){
        $code = rand('100000','999999');
        $captcha = intval($_POST['captcha']);
        $mobile = intval($_POST['mobile']);
        ($_SESSION['captcha'] == $captcha && $_SESSION['mobile'] == $mobile) ? $result['error']=0 : $result['error']=1;
    }else{
        $result['error']=1;
    }
    echo $json->encode($result);
    exit;
}

elseif($action == 'check_mobile'){
    $mobile = intval($_REQUEST['mobile']);
    $sql = "SELECT COUNT(*) FROM " . $ecs->table('users') .
        " WHERE mobile_phone = '$mobile' OR user_name = '$mobile' OR email = '$mobile'";
    $db->getOne($sql) == 0 ? $result='ok' : $result=1;
    echo $result;
    exit;
}

elseif($action == 'is_exchange'){
    /* 取得刮刮乐商品列表，计算合计 */
    $user_id= $_SESSION['user_id'];
    if(!empty($user_id)){
    $sql="SELECT c.*,g.goods_thumb FROM ".$GLOBALS['ecs']->table('cart')." AS c".
        " LEFT JOIN ".$GLOBALS['ecs']->table('guadanle')." AS gu".
        " ON c.extension_code = gu.cdkey AND c.user_id = gu.user_id ".
        " LEFT JOIN ".$GLOBALS['ecs']->table('goods')." AS g".
        " ON g.goods_id = c.goods_id ".
        "WHERE c.extension_code > 0 AND c.user_id = ".$_SESSION['user_id'];

    $exchange_goods=$db->getALL($sql);
    $smarty->assign('exchange_goods', $exchange_goods);
    
    }
    $result['content'] = $smarty->fetch("library/alone.lbi");
    echo $json->encode($result);
    exit;
}

elseif($action == 'gift_goods_list'){
    /* 获取双11赠品 */
    require(dirname(__FILE__) . '/includes/lib_gift.php');
    $order = flow_order_info();
    $cart_goods = cart_goods();

    /* 删除购物车里面的extension_code键值 */
    foreach ($cart_goods as $key => $value) {
        if($value['extension_code']){ 
            $exchange_goods[] = $value;
            unset($cart_goods[$key]);
        }
    }
    $smarty->assign('goods_list', $cart_goods);           //购物车商品列表
    $smarty->assign('exchange_goods', $exchange_goods);   //刮蛋乐商品列表
    $smarty->assign('order', $order);
    /*
    * 计算订单的费用
    */
    $order['daodansong_id'] = $_SESSION['flow_consignee']['daodansong']['area_id'];
    
    $total = order_fee($order, $cart_goods, $consignee);
    $smarty->assign('total', $total);
    $gift_goods_list = get_gift_goods_list($total['goods_price'],'','','',$_SESSION['flow_consignee']['area_id']);
    $smarty->assign('gift_goods_list', $gift_goods_list);
    $result['content'] = $smarty->fetch("library/gift_goods_list.lbi");
    echo $json->encode($result);
    exit;
}
elseif($action == 'ctock_remind_goods_list'){
    /* 获取双11赠品 */
    $sql = "SELECT * FROM " . $ecs->table('goods') . " WHERE goods_id != $_POST[goods_id] AND cat_id = $_POST[cat_id] limit 4";
    $goods_list = $db->getAll($sql);
    $smarty->assign('goods_list', $goods_list);
    $result['content'] = $smarty->fetch("library/ctock_remind_goods_list.lbi");
    echo $json->encode($result);
    exit;
}

/* 选择默认地址并返回计算数据 */
elseif ($action == 'select_address') {
    $address_id = !empty($_REQUEST['address_id'])?$_REQUEST['address_id']:exit;
    //设定为默认地址
    $sql =  " UPDATE  ".$ecs->table('users').
            " set address_id = '$address_id'".
            " WHERE user_id = '$_SESSION[user_id]'";
    $db->query($sql);
    echo $json->encode($address_id);
    exit();
}
else{
    header('location:index.php');
}

?>